const util = require('../../utils/util');
const PrintService = require('../../service/system/print.service');

async function createPrint(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { title } = ctx.request.body;

	if (!title) {
		return util.fail(ctx, '标题不能为空');
	}

	try {
		const result = await PrintService.createPrint({ title, create_id: userId, updata_id: userId });
		util.success(ctx, { id: result.id });
	} catch (error) {
		util.fail(ctx, error.message || '创建失败');
	}
}

async function deletePrints(ctx) {
	const { ids } = ctx.request.body;

	if (!Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '模板 ID 列表无效');
	}

	try {
		await PrintService.deletePrints(ids);
		util.success(ctx);
	} catch (error) {
		util.fail(ctx, error.message || '删除失败');
	}
}

async function updatePrint(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, title } = ctx.request.body;

	if (!id || !title) {
		return util.fail(ctx, '模板 ID 或标题不能为空');
	}

	try {
		await PrintService.updatePrint({ id, title, updata_id: userId });
		util.success(ctx);
	} catch (error) {
		util.fail(ctx, error.message || '更新失败');
	}
}

async function getPrintList(ctx) {
	const { page = 1, limit = 10, title } = ctx.query;

	try {
		const result = await PrintService.getPrintList({
			page: parseInt(page),
			limit: parseInt(limit),
			title,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, error.message || '查询失败');
	}
}

async function getPrintTemplate(ctx) {
	const { id } = ctx.query;

	if (!id) {
		return util.fail(ctx, '模板 ID 无效');
	}

	try {
		const result = await PrintService.getPrintTemplate(parseInt(id));
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, error.message || '查询模板失败');
	}
}

async function savePrintTemplate(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, template } = ctx.request.body;

	if (!id || !template) {
		return util.fail(ctx, '模板 ID 或内容不能为空');
	}

	try {
		await PrintService.savePrintTemplate({ id, template, updata_id: userId });
		util.success(ctx);
	} catch (error) {
		console.error('Save print template error:', error.message);
		util.fail(ctx, error.message || '保存模板失败');
	}
}

module.exports = {
	createPrint,
	deletePrints,
	updatePrint,
	getPrintList,
	getPrintTemplate,
	savePrintTemplate,
};
